package test.src.awt_swing;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class JSplitPaneDemo {
    JFrame jFrame = new JFrame("这里测试JSplitPane");

    Book[] books = new Book[]{
            new Book("JAVA自学宝典",
                    "test\\src\\awt_swing\\img\\container\\java.png",
                    "国内关于 Java 编程最全面的图书 \n 看得懂 ， 学得会"),
            new Book("轻量级的JAVAEE企业应用实战",
                    "test\\src\\awt_swing\\img\\container\\ee.png",
                    "SSM整合开发的经典图书，值的拥有"),
            new Book("Android基础教程",
                    "test\\src\\awt_swing\\img\\container\\android.png",
                    "全面介绍Android平台应用程序\n 开发的各方面知识")
    };

    BufferedImage image;

    private class MyCanvas extends JPanel {
        @Override
        public void paint(Graphics g) {
            g.drawImage(image, 0, 0, null);
        }
    }

    MyCanvas drawArea = new MyCanvas();

    JList<Book> bookJList = new JList<>(books);

    JTextArea jTextArea = new JTextArea();

    private void init() {
        //组装视图
        drawArea.setPreferredSize(new Dimension(220, 330));
        jTextArea.setPreferredSize(new Dimension(220, 70));
        bookJList.setPreferredSize(new Dimension(150, 400));

        bookJList.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                Book book = bookJList.getSelectedValue();
                try {
                    image = javax.imageio.ImageIO.read(new File(book.getDir()));
                    drawArea.repaint();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                jTextArea.setText(book.getIntroduce());
            }
        });

        JSplitPane left = new JSplitPane(JSplitPane.VERTICAL_SPLIT, drawArea, new JScrollPane(jTextArea));
        left.setOneTouchExpandable(true);
        left.setContinuousLayout(true);
        left.resetToPreferredSizes();

        JSplitPane content = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, left, bookJList);
        content.setContinuousLayout(true);

        jFrame.add(content);
        jFrame.pack();
        jFrame.setVisible(true);
    }

    public static void main(String[] args) {
        new JSplitPaneDemo().init();
    }
}
